package com.fwtai.service.api;

import com.fwtai.api.ApiPromotionDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.LocalUserId;
import com.fwtai.tool.ToolClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 促销营销活动
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-04-04 17:45:50
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiPromotionService{

  private final ApiPromotionDao apiPromotionDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public ApiPromotionService(final ApiPromotionDao apiPromotionDao,final ThreadPoolTaskExecutor taskExecutor){
    this.apiPromotionDao = apiPromotionDao;
    this.taskExecutor = taskExecutor;
  }

  public String getShopInfo(){
    final String loginId = LocalUserId.get();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null){
        return ToolClient.accessLogin();
      }
      return ToolClient.queryJson(apiPromotionDao.getShopInfo(Long.parseLong(loginId)));
    },taskExecutor).join();
  }

  public String getpromotionInfo(final Long kid){
    final String loginId = LocalUserId.get();
    return CompletableFuture.supplyAsync(()->{
      if(loginId == null){
        return ToolClient.accessLogin();
      }
      final HashMap<String,Object> info = apiPromotionDao.getpromotionInfo(kid);
      final List<HashMap<String,Object>> list = apiPromotionDao.getpromotionGoods(kid,Long.parseLong(loginId));
      final HashMap<String,Object> result = new HashMap<>(2);
      result.put("info",info);
      result.put("list",list);
      return ToolClient.queryJson(result);
    },taskExecutor).join();
  }

  /**适用于api接口,仅含数据不含总记录数总条数*/
  public String listData(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = ToolClient.pageParamsApi(request);
      if(formData == null) return ToolClient.jsonValidateField();
      return ToolClient.jsonPage(apiPromotionDao.getListData(formData));
    },taskExecutor).join();
  }

  public String getStorePromotion(final Long activityId,final Long storeId){
    return CompletableFuture.supplyAsync(()->{
      final HashMap<String,Object> info = apiPromotionDao.getpromotionInfo(activityId);
      final List<HashMap<String,Object>> list = apiPromotionDao.getStorePromotion(activityId,storeId);
      final HashMap<String,Object> result = new HashMap<>(2);
      result.put("info",info);
      result.put("list",list);
      return ToolClient.queryJson(result);
    },taskExecutor).join();
  }
}